package com.sn.author.monitor.handler;

import com.alibaba.fastjson.JSON;
import com.sn.author.common.exception.BadRequestException;
import com.sn.author.common.sdk.AbstractResponse;
import com.sn.author.common.sdk.response.VideoInfoResponse;
import com.sn.author.domain.entity.ImportVideo;
import com.sn.author.domain.taskEntity.TaskModel;
import com.sn.author.domain.taskEntity.VideoInfo;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VideoInfoHandler extends AbsHandler{

    public VideoInfoHandler(TaskModel taskModel) {
        super(taskModel);
    }

    @Override
    public void execute() throws Exception {
        super.execute();
    }

    @Override
    String getErrorMessage(String errmsg) {
        return null;
    }

    @Override
    AbstractResponse requestApi() {
        VideoInfo videoInfo = JSON.parseObject(taskModel.getTaskParam().toString(),VideoInfo.class);
        return getSdkService().executeGetVideoInfoSdk(videoInfo.getUrl());
    }

    @Override
    String getSuccessMessage() {
        VideoInfo videoInfo = JSON.parseObject(taskModel.getTaskParam().toString(),VideoInfo.class);
        return "获取视频:[" + videoInfo.getUrl() + "] 信息成功" ;
    }

    @Override
    public void responseAfter(AbstractResponse response) {
        VideoInfo videoInfo = JSON.parseObject(taskModel.getTaskParam().toString(),VideoInfo.class);
        //更新视频数据
        VideoInfoResponse videoInfoResponse = (VideoInfoResponse)response;
        VideoInfoResponse.ResponseMsgResult data = videoInfoResponse.getData();
        log.info("更新视频数据信息：url:{} info:{}",videoInfo.getUrl(),data);
        if(data == null){
            throw new BadRequestException("获取视频:[" + videoInfo.getUrl() + "] API返回的数据为空");
        }
        //更新视频信息
        getVideoService().updateVideoInfoByUrl(videoInfo.getUrl(),buildVideoModel(data));
        log.info("更新视频：[{}] \n 视频信息:[{}] ",videoInfo.getUrl(),JSON.toJSONString(data));
    }

    private ImportVideo buildVideoModel(VideoInfoResponse.ResponseMsgResult data){
        ImportVideo video = new ImportVideo();
        video.setAttentionCnt(Long.parseLong(data.getStatistics().getAttention_count() == null || data.getStatistics().getAttention_count().isEmpty() ? "0" : data.getStatistics().getComment_count()));
        video.setLikeCnt(Long.parseLong(data.getStatistics().getDigg_count().isEmpty() ? "0" : data.getStatistics().getDigg_count()));
        video.setVideoId(data.getUid().isEmpty() ? "0" : data.getUid());
        video.setTitle(data.getTitle());
        video.setAuthorName(data.getNickname());
        log.debug("build model:{}",JSON.toJSONString(video));
        return video;
    }

    @Override
    public void responseErrAfter(String errMsg) {

    }

    @Override
    boolean isPushMessage() {
        return false;
    }
}
